<?php


//用于测试打印数组数据
function p($arr){
    header('content-type:text/html;charset=utf-8');
    echo '<pre>';
    print_r($arr);
    echo '</pre>';
}
/**
 * 用于API调式时输出LOG文件
 * @param mixed $value 要打印的数年据
 * @param string $file 文件要保存的完整路径, 含文件名, 默认在当前控制器目录下同名.log
 * @return null 无返回值
 * by zhaojiping liuniukeji.com
 */
function LL($value='', $file=''){
    if ($file == '') {
        $file = './Application/'. MODULE_NAME .'/Controller/'. CONTROLLER_NAME .'Controller.class.log';
    }
    error_log(print_r($value,1),3, $file);
}

/**
 * 密码加密与密码验证
 * @param string $str_password  需要加密的密码字符串
 * @param string $real_password 需要验证的密码字符串
 * @param boolean $type 操作类型  false[密码加密]  true[密码验证]
 * @return mixed
 */
function pwdHash($str_password='',$real_password='',$type=false){
    if(!$str_password && !$real_password) return false;
    require_cache(PLUGINS.'/Phpass/PasswordHash.php');
    $hasher = new PasswordHash(8, false);
    if(!$type){
        return $hasher->HashPassword($str_password);
    }else{
        return $hasher->CheckPassword($str_password, $real_password);
    }
}


/**
 * 密码加密与密码验证
 * @param string $str_password  需要加密的密码字符串
 * @return mixed
 */
function yunshangPasswordEncode($str_password=''){
    return md5($str_password);
}

// /**
// * 金额格式化
// * @param string $money 需要格式化的金额
//  * @param string $sep 千位分隔符
// * @return string
// */
// function money_format($money = NULL,$sep=','){
//     $money = $money === NULL ? '0.00' : floatval($money);
//     return number_format($money, 2, '.', $sep);
// }

/**
 * XSS安全过滤
 * @param string $content 需要过滤的内容
 * @return string
 */
function filter_xss($content){
    require_cache(PLUGINS.'/HTMLPurifier/HTMLPurifier.includes.php');
    $config = HTMLPurifier_Config::createDefault();
    $config->set('HTML.TargetBlank', TRUE);
    $obj = new HTMLPurifier($config);
    return $obj->purify($content);
}

/**
 * 时间戳格式化
 * @param int $time
 * @return string 格式化后的时间字符串
 */
function time_format($time = NULL,$style='Y-m-d H:i:s'){
    $time = $time === NULL ? NOW_TIME : intval($time);
    return date($style, $time);
}

/**
 * 手机格式验证
 * @param string $mobile 验证的手机号码
 * @return boolean
 */
function is_mobile($mobile){
    if ( !empty($mobile) ) {
        return preg_match('/^1[3|4|5|7|8][0-9]\d{8}$/', $mobile);
    }
    return false;
}

/**
 * 电子邮箱格式验证
 * @param  string $email 验证的邮件地址
 * @return boolean
 */
function is_email($email) {
    if ( !empty($email) ){
        return preg_match('/^[a-z0-9]+([\+_\-\.]?[a-z0-9]+)*@([a-z0-9]+[\-]?[a-z0-9]+\.)+[a-z]{2,6}$/i', $email);
    }
    return false;
}

/**
 * 通用分页处理函数
 * @param Int $count 总条数
 * @return Array  ['page']分页数据  ['limit']查询调用的limit条件
 */
function get_page($count){
    $page = new \Think\Page($count,C('PER_PAGE_COUNT'));
    $page -> setConfig('header',C('PAGE_HEADER'));
    $page -> setConfig('first',C('PAGE_FIRST'));
    $page -> setConfig('last',C('PAGE_LAST'));
    $page -> setConfig('prev',C('PAGE_PREV'));
    $page -> setConfig('next',C('PAGE_NEXT'));
    $page -> setConfig('theme',C('PAGE_THEME'));
    $show = $page->show();
    $limit = $page->firstRow.','.$page->listRows;
    return array('page'=>$show,'limit'=>$limit);
}


/**
 * TODO 基础分页的相同代码封装，使前台的代码更少
 * @param $count 要分页的总记录数
 * @param int $pagesize 每页查询条数
 * @return \Think\Page
 */
function getpage($count, $pagesize = 10) {
    $p = new Think\Page($count, $pagesize);
    $p->setConfig('header', '<li class="rows">共<b>%TOTAL_ROW%</b>条记录&nbsp;第<b>%NOW_PAGE%</b>页/共<b>%TOTAL_PAGE%</b>页</li>');
    $p->setConfig('prev', '上一页');
    $p->setConfig('next', '下一页');
    $p->setConfig('last', '末页');
    $p->setConfig('first', '首页');
    $p->setConfig('theme', '%FIRST%%UP_PAGE%%LINK_PAGE%%DOWN_PAGE%%END%%HEADER%');
    $p->lastSuffix = false;//最后一页不显示为总页数
    return $p;
}

/**
 * 通用图片上传函数
 * @param string $imgname 上传文件域的NAME属性
 * @param string $dirname  上传文件存储目录
 * @param array $thumb    需要生成多少个缩略图
 * @return array
 */
function upload($imgname,$dirname,$thumb=array()){
    if(isset($_FILES[$imgname]) && $_FILES[$imgname]['error'] == 0){
        $upload = new \Think\Upload();
        $rootpath = C('UPLOAD_ROOTPATH');
        $upload->savePath = $rootpath;
        // $upload->maxSize = intval(C('IMAGE_MAXSIZE'))*1024*1024;
        $upload->maxSize = 20097152 ;
        $upload->exts = array('jpg', 'pjpeg', 'bmp', 'gif', 'png', 'jpeg', 'zip', 'apk', 'rar', 'mp4');
        $upload->savePath = $dirname.'/';
        $info = $upload->upload(array($imgname=>$_FILES[$imgname]));
        if(!$info){
            return array('status'=>0,'error'=>$upload->getError());
        }else{
            $ret['status'] = 1;
            $ret['image']['origin'] = $origin_img = $info[$imgname]['savepath'].$info[$imgname]['savename'] ;
            if(is_array($thumb) && !empty($thumb)){
                $image = new \Think\Image();
                foreach($thumb as $k => $v){
                    $ret['image']['thumb'][$k] = $info[$imgname]['savepath'].'thumb_'.$k.'_'.$info[$imgname]['savename'];
                    $image->open($rootpath.$origin_img);
                    $image->thumb($v[0],$v[1])->save($rootpath.$ret['image']['thumb'][$k]);
                }
            }
        }
        return $ret;
    }
}
function upload1($imgname,$dirname,$thumb=array()){
    if(isset($_FILES[$imgname]) && $_FILES[$imgname]['error'] == 0){
        $upload = new \Think\Upload();
        $rootpath = C('UPLOAD_ROOTPATH');
        $upload->savePath = $rootpath;
        $upload->maxSize = intval(C('IMAGE_MAXSIZE'))*1024*1024;
        $upload->exts = C('ALLOW_IMG_EXT');
        $upload->savePath = $dirname.'/';
        $info = $upload->upload(array($imgname=>$_FILES[$imgname]));
        if(!$info){
            return array('status'=>0,'error'=>$upload->getError());
        }else{
            print_r($info);
            $ret['status'] = 1;
            $ret['image']['origin'] = $origin_img = $info[$imgname]['savepath'].$info[$imgname]['savename'] ;
            if(is_array($thumb) && !empty($thumb)){
                $image = new \Think\Image();
                foreach($thumb as $k => $v){
                    $ret['image']['thumb'][$k] = $info[$imgname]['savepath'].'thumb_'.$k.'_'.$info[$imgname]['savename'];
                    $image->open($rootpath.$origin_img);
                    $image->thumb($v[0],$v[1])->save($rootpath.$ret['image']['thumb'][$k]);
                }
            }
        }
        return $info;
    }
}
/**
 * 验证上传文件域中是否有上传的图片
 * @param String $imgname
 * @return Boolean
 */
function has_img($imgname){
    foreach($_FILES[$imgname]['error'] as $v){
        if($v == 0){
            return true;
        }
    }
    return false;
}

/**
 * 生成文件扩展名, 如果没有传文件的名称
 * @param $ext: 生成文件默认文件名称
 */
function createFileName($ext='png'){
    return date('Ymd_His') .'_'. microtime(true)*10000 .'_' . rand(1000,9999) .'.' . $ext;
}

/**
 * 手机图片上传
 * @param $img: 旧图片地址
 * @param $obj: 上传的表单名称
 * @param $path: 上传的文件目录
 * @return mixed 上传成功, 返回上传的图片地址, 上传失败返加-1或0
 */
function app_upload_img($obj='photo', $img='',  $path='Community', $uid=UID){
    if (isset($_FILES[$obj]['tmp_name']) && !empty($_FILES[$obj]['tmp_name'])) {

        // 旧图片地址得到图片名称
        $img = basename($img);
        if ($img == '' || empty($img) || $img == null) {
            $img = createFileName('jpg');
        }

        $createImgPath = '.'. C('IMG_URL') .'/'. $uid ;
        if ( !is_dir($createImgPath) ) {
            mkdir($createImgPath);
        }

        if ($path != '') {
            $createImgPath = $createImgPath .'/'. $path;
            if ( !is_dir($createImgPath) ) {
                mkdir($createImgPath);
            }
        }

        $target_path = $createImgPath .'/'. $img ; //接收文件目录
        // error_log($target_path, 3,__FILE__. time(). '.html');
        if (move_uploaded_file( $_FILES[$obj]['tmp_name'], $target_path )) {
            if (substr($target_path, 0, 1) == '.') {
                $target_path = substr($target_path, 1);
            }
            return $target_path;
        } else {
            return -1;
        }
    } else {
        return 0;
    }
}

/**
 * 删除指定的图片
 * @param [Array|String] $images 需要删除的图片
 * @return Boolean
 */
function deleteImage($images=''){
    if(empty($images))
        return;
    $path = C('UPLOAD_ROOTPATH');
    if(is_array($images)){
        foreach ($images as $v){
            $file = $path.$v;
            if(file_exists($file))
                @unlink($path.$v);
        }
    }else{
        @unlink($path.$images);
    }
}

/**
 * 显示图片信息
 * @param string $url 图片地址
 * @param type $width 设定图片宽度
 * @param type $height 设定图片高度
 * @return String
 */
function showImage($url, $width='', $height=''){
    if(empty($url))
        return ;
    $url = C('IMG_URL').$url;
    if($width)
        $width = "width='$width'";
    if($height)
        $height = "height='$height'";
    echo "<img class='thumbnail' src='$url' $width $height />";
}

/**
 * 生成日期与随机数字的字符串, 用下划线分隔
 * @return String 日期_时间_毫秒微秒_4位随机数
 * example 上传的文件名, 环信用户的用户名
 */
function datetimeRand(){
    return date('Ymd_His') .'_'. rand(100000,999999);
}

/*
 * 生成随机字符串
 * @param int $length 返回的字符串的长度, 默认16位
 * @return String
 * example: 环信用户的密码
 */
function randChar($length = 16){
    $str = '';
    $strPol = 'abcdefghigkmnpqrstuvwxyz23456789';
    $max = strlen($strPol)-1;

    for($i=0; $i<$length; $i++){
        $str .= $strPol[rand(0, $max)];  //rand($min,$max)生成介于min和max两个数之间的一个随机整数
    }

    return $str;
}

/**
 * [get_global_config 获取配置]
 * @return [type] [description]
 */
function get_global_config()
{
    /* 读取数据库中的配置 */
    $config =   S('DB_CONFIG_DATA');
    if(!$config){
        $configParse = new \Common\Tools\ConfigParse();
        $config      =   $configParse->lists();
        S('DB_CONFIG_DATA',$config);
    }
    C($config); //添加配置

}
/**
 * [getMillisecond 获取毫秒级时间戳]
 * @return [type] [description]
 */
function getMillisecond() {
    list($t1, $t2) = explode(' ', microtime());
    return (float)sprintf('%.0f',(floatval($t1)+floatval($t2))*1000);
}

/**
 * 获取图片缩略图
 * 如果缩略图不存在则生成
 * @param String $filename 文件存放位置
 * @param int 缩略图宽度
 * @param int 缩略图高度
 */
function thumb($filename, $width=120, $height=120){
    if ($filename == '') {
        return '';
    }
    $info = pathinfo($filename);

    // 如果图片已经是缩略图, 直接返回
    $thumbFlag = '_' . $width .'_'. $height;
    $thumbFlagLen = strlen($thumbFlag);
    if (substr($info['filename'], -$thumbFlagLen) == $thumbFlag && file_exists($filename)) {
        return '/' . $filename;
    }

    $oldFile = $info['dirname'] . DIRECTORY_SEPARATOR . $info['filename'] . '.' . $info['extension'];
    $thumbFile = $info['dirname'] . DIRECTORY_SEPARATOR . $info['filename'] . $thumbFlag .'.' . $info['extension'];

    $oldFile = str_replace('\\', '/', $oldFile);
    $thumbFile = str_replace('\\', '/', $thumbFile);

    $filename = ltrim($filename, '/');
    $oldFile = ltrim($oldFile, '/');
    $thumbFile = ltrim($thumbFile, '/');

    //如果原图不存在, 清除缩略图, 返回原图地址
    if (!file_exists($oldFile)) {
        @unlink($thumbFile);
        return '/' . $oldFile;

    }else if(file_exists($thumbFile)){ //缩图已存在, 直接返回缩略图
        return '/' . $thumbFile;

    }else{ //生成缩略图
        $oldimageinfo = getimagesize($oldFile);
        $old_image_width = intval($oldimageinfo[0]);
        $old_image_height = intval($oldimageinfo[1]);
        if ($old_image_width <= $width && $old_image_height <= $height) {
            @unlink($thumbFile);
            @copy($oldFile, $thumbFile);

            return '/' . $thumbFile;

        } else {
            $image = new \Think\Image();
            if ($old_image_width < $old_image_height) {
                $myHeight = $old_image_height * $width / $old_image_width;
                // 压缩
                $image->open($oldFile)->thumb($width, $myHeight, \Think\Image::IMAGE_THUMB_SCALE)->save($thumbFile, null, 100, false);
            } else {
                $myWidth = $old_image_width * $height / $old_image_height;
                // 压缩
                $image->open($oldFile)->thumb($myWidth, $height, \Think\Image::IMAGE_THUMB_SCALE)->save($thumbFile, null, 100, false);
            }

            if (intval($height) == 0 || intval($width) == 0) {
                exit('/' . $oldFile);
            }
            //dump($image);exit;
            // 再居中截取
            $image->open($thumbFile)->thumb($width, $height, \Think\Image::IMAGE_THUMB_CENTER)->save($thumbFile, null, 95, false);

            //缩图失败
            if (!$image) {
                $thumbFile = $oldFile;
            }

            return '/' . $thumbFile;
        }
    }
}

function app_upload_img1($obj='photo', $img='',  $path='Community', $uid=UID){
    if (isset($_FILES[$obj]['tmp_name']) && !empty($_FILES[$obj]['tmp_name'])) {
        for($i=0;$i<count($_FILES[$obj]['tmp_name']);$i++){
            // 旧图片地址得到图片名称
            $img[$i]= basename($img[$i]);
            if ($img[$i] == '' || empty($img[$i]) || $img[$i] == null) {
                $img[$i] = createFileName('jpg');
            }

            $createImgPath[$i] = '.'. C('IMG_URL') .'/'. $uid ;
            if ( !is_dir($createImgPath[$i]) ) {
                mkdir($createImgPath[$i]);
            }

            if ($path[$i] != '') {
                $createImgPath[$i] = $createImgPath[$i] .'/'. $path[$i];
                if ( !is_dir($createImgPath[$i]) ) {
                    mkdir($createImgPath[$i]);
                }
            }

            $target_path[$i] = $createImgPath[$i] .'/'. $img[$i] ; //接收文件目录
            // error_log($target_path, 3,__FILE__. time(). '.html');
            if (move_uploaded_file( $_FILES[$obj]['tmp_name'][$i], $target_path[$i] )) {
                if (substr($target_path[$i], 0, 1) == '.') {
                    $target_path[$i] = substr($target_path[$i], 1);
                }
                return $target_path[$i];
            } else {
                return -1;
            }
        }

    } else {
        return 0;
    }
}

/**
 * 极光推送通用消息
 * @param string $alert  提示标题
 * @param string $type 信息类型
 * @param string|array $userId 用户id 可传数组
 * @param string $msg  信息内容
 * @param string $title  信息标题
 * @return string
 */
function jPush( $alert, $type, $userId = null, $msg = '') {
    require_once ("./Plugins/JPush/JPush.php");
    try {
        $client = new \JPush ( C ( 'USER_PUSH_APIKEY' ), C ( 'USER_PUSH_SECRETKEY' ) );

        $extras = array (
            'type' => $type,
            'alert' => $alert,
            'content' => $msg
        );

        /* @var $client PushPayload */
        $client = $client->push ();
        $client = $client->setPlatform ( 'all' );
        $client = $client->setNotificationAlert ( $alert );
        $client = $client->addIosNotification ( $alert, 'default', null, null, null, $extras );
        //$client = $client->setMessage ( $alert, $alert, 'type', $extras );
        $client = $client->addAndroidNotification ( $alert, $alert, null, $extras );
        $client = $client->setOptions ( 100000, 3600, null, false ); //测试环境
        //$client = $client->setOptions ( 100000, 3600, null, true ); //生产环境
        if ($userId) {
            // $client = $client->addRegistrationId ( $registrationIds );
            $client->addAlias ( $userId );
        } else {
            $client = $client->addAllAudience ();
        }

        $result = $client->send ();
        // echo 'Result=' . json_encode ( $result ) . $br;
        return json_encode ( $result );
    }catch (\Exception $e){
        return $e->getMessage();
    }
}
function jPushs( $alert, $type, $userId, $msg = '') {
    require_once ("./Plugins/JPush/JPush.php");
    try {
        $client = new \JPush ( C ( 'USER_PUSH_APIKEY' ), C ( 'USER_PUSH_SECRETKEY' ) );

        $extras = array (
            'type' => $type,
            'alert' => $alert,
            'content' => $msg
        );

        $client = $client->push ();
        $client = $client->setPlatform ( 'all' );
        $client = $client->setNotificationAlert ( $alert );
//        $client = $client->addIosNotification ( $alert, 'ios sound', 0, true, 'iOS category', $extras );
        //$client = $client->setMessage ( $alert, $alert, 'type', $extras );
        $client = $client->addAndroidNotification ( $alert, $alert, null, $extras );
        $client = $client->setOptions ( 100000, 3600, null, false ); //测试环境
        //$client = $client->setOptions ( 100000, 3600, null, true ); //生产环境
        if ($userId) {
            $client = $client->addRegistrationId ($userId );
            // $client->addAlias ( $userId );
        } else {
            $client = $client->addAllAudience ();
        }

        $result = $client->send ();
        // echo 'Result=' . json_encode ( $result ) . $br;
        return json_encode ( $result );
    }catch (\Exception $e){
        return $e->getMessage();
    }
}
// function sensitive($content){
//     $wordArr = include 'SensitiveThesaurus.php';
//     foreach ($wordArr as $row){
//         if (false !== strstr($content,$row)){
//             return true;
//         }else{
//             return false;
//         }
//     }
//     return true;
// }
function sensitive($str){
    $allergicWord = require(APP_PATH . '/Common/Common/SensitiveThesaurus.php');
    foreach ($allergicWord as $word) {
        if (mb_strpos($str, $word) > -1) {
            $str = preg_replace('/' . $word . '/', '***', $str);
        }
    }
    /*for ($i=0;$i<count($allergicWord);$i++){
        //根据字符串的长度,加*
        $replace = '';
        for($j=0; $j<mb_strlen($allergicWord[$i]); $j++){
            $replace .= '*';
        }
        $str =  str_replace($allergicWord[$i], $replace, $str);
    }*/
    return $str;
}

function getFile($url,$save_dir='',$filename='',$type=0){
    if(trim($url)==''){
        return false;
    }
    if(trim($save_dir)==''){
        $save_dir='./';
    }
    if(0!==strrpos($save_dir,'/')){
        $save_dir.='/';
    }
    //创建保存目录
    if(!file_exists($save_dir)&&!mkdir($save_dir,0777,true)){
        return false;
    }
    //获取远程文件所采用的方法
    if($type){
        $ch=curl_init();
        $timeout=5;
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
        $content=curl_exec($ch);
        curl_close($ch);
    }else{
        ob_start();
        readfile($url);
        $content=ob_get_contents();
        ob_end_clean();
    }
    $size=strlen($content);
    //文件大小
    $fp2=@fopen($save_dir.$filename,'a');
    fwrite($fp2,$content);
    fclose($fp2);
    unset($content,$url);
    return array('file_name'=>$filename,'save_path'=>$save_dir.$filename);
}

/**
 * 使用CURL发送POST请求
 * @param string $param 发送的数据
 * @param string $url 发送地址
 * @return string
 */
function request_post($url = '', $param = '') {
    if (empty($url) || empty($param)) {
        return false;
    }
    $postUrl = $url;
    $curlPost = $param;
    $ch = curl_init();//初始化curl
    curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
    curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
    curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
    curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
    $data = curl_exec($ch);//运行curl
    curl_close($ch);

    return $data;
}

function input_csv($handle)   
{   
    $out = array ();   
    $n = 0;   
    while ($data = fgetcsv($handle, 10000))   
    {   
        $num = count($data);   
        for ($i = 0; $i < $num; $i++)   
        {   
            $out[$n][$i] = $data[$i];   
        }   
        $n++;   
    }   
    return $out;   
} 

/**
 * 发送短信
 * @param $phone string 手机号
 * @param $msg string 内容
 * @return string
 */
function send_sms($phone, $msg = '您收到一条待办通知，请及时登录安监平台APP处理。')
{
	$url = 'http://yxt.wxtxsms.cn:8181/dx/sendPostExt.do';
	$post_data['uid']       = 'lylt';                  //用户ID
	$post_data['upsd']      = strtolower(md5('lylt@888')) ;   //密码
	$post_data['sendtele']  = $phone;                       //发送号码
	$post_data['msg']       = $msg;                //短信内容
	$post_data['sign']      = '星澜网络';                     //签名
	$post_data['ext'] = '';

	$o = "";
	foreach ( $post_data as $k => $v )
	{
		$o.= "$k=" . urlencode( $v ). "&" ;
	}
	$post_data = substr($o,0,-1);
	return request_post($url, $post_data);
}

